package org.example.test;

import org.example.test.service.ChildrensRentalStartegyImpl;
import org.example.test.service.NewReleaseRentalStartegyImpl;
import org.example.test.service.RegularRentalStartegyImpl;
import org.example.test.service.RentalStrategy;

import java.math.BigDecimal;
import java.util.*;

/**
 * 	顾客
 */
public class Customer {
	// 顾客名称
	private String name;
	// 租赁信息  Vector时线程安全的但性能差，这里只有读，用List即可
	private List<Rental> rentals;

	// spring环境可依赖注入策略 此次暂时用静态加载方式
	private static List<RentalStrategy> strategies;

	public Customer(String name, List rentals) {
		this.name = name;
		this.rentals = rentals;
		// 依赖注入时getStrategies不需要
		getStrategies();
	}

	private static void getStrategies(){
		strategies = new ArrayList();
		strategies.add(new RegularRentalStartegyImpl());
		strategies.add(new NewReleaseRentalStartegyImpl());
		strategies.add(new ChildrensRentalStartegyImpl());
	}

	public String getName() {
		return this.name;
	}

	public void addRental(Rental arg) {
		this.rentals.add(arg);
	}

	/**
	 *
	 * @return
	 */
	public String statement() {
		// 金额
		BigDecimal totalAmount = new BigDecimal("0");
		// 积分
		int frequentRenterPoints = 0;
		// 遍历
		Iterator rentals = this.rentals.iterator();
		StringBuilder result = new StringBuilder("<H1>Rentals for <EM>").append(getName()).append("</EM></H1><P>\n");
		while (rentals.hasNext()) {
			Rental each = (Rental) rentals.next();
			BigDecimal thisAmount = new BigDecimal("0");
			// 根据策略计算金额和积分
			for (RentalStrategy  strategy:strategies) {
				// 金额
				BigDecimal bigDecimal = strategy.calculateAmount(each);
				if(bigDecimal!=null) {
					thisAmount = thisAmount.add(bigDecimal);
				}

				// 积分
				Integer points = strategy.calculatePoints(each);
				if(points!=null) {
					frequentRenterPoints +=points;
				}
			};

			//show figures for this rental
			result.append(each.getMovie().getTitle()).append(": ").append(String.valueOf(thisAmount)).append("<BR>\n");
			totalAmount = totalAmount.add(thisAmount);
		}
		//add footer lines
		result.append("<P>You owe <EM>").append(String.valueOf(totalAmount)).append("</EM><P>\n");
		result.append( "On this rental you earned <EM>").append(String.valueOf(frequentRenterPoints)).append("</EM> frequent renter points<P>");
		return result.toString();
	}
}
